from django.core.paginator import *
from django.http import Http404
from django.shortcuts import render_to_response, render
from jiqixuexi.cms.models import *


def index_data():
    articles = Article.objects.order_by('-create_at')[0:10]
    return {'articles': articles, 'ctx': contexts()}


def index(request):
    return render_to_response('index.html', index_data())


def page_data(page):
    article_all = Article.objects.all()
    paginator = Paginator(article_all, 10)
    try:
        page = int(page)
        articles = paginator.page(page)
    except PageNotAnInteger:
        articles = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        articles = paginator.page(paginator.num_pages)
    except ValueError:
        raise Http404()
    return articles


def page(request, page):
    return render_to_response('index.html', page_data(page))


def categories_data(cat, page):
    article_all = Article.objects.filter(categories__id=cat)
    paginator = Paginator(article_all, 10)
    # page = request.GET.get('page')
    try:
        page = int(page)
        articles = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        articles = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        articles = paginator.page(paginator.num_pages)
    except ValueError:
        raise Http404()
    return articles


def categories(request, cat, page):
    return render_to_response('index.html', categories_data(cat, page))


def view_article_data(article):
    return {'article': article, 'ctx': contexts()}


def view_article(request, article_id):
    article = Article.objects.get(id=article_id)
    return render(request, 'article.html', view_article_data(article))


def contexts():
    hot = Article.objects.order_by('view_count')[0: 10]
    cats = Category.objects.filter(parent_id=1)
    links = Link.objects.order_by('-weight')
    menu = Menu.objects.order_by('-weight')
    return {'hot': hot, 'categories': cats, 'links': links, 'menu': menu}